<template>
  <div class="modules-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>模块管理</span>
          <el-button type="primary" @click="refreshWidgets">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-section">
        <div class="search-controls">
          <el-input
            v-model="searchQuery"
            placeholder="搜索组件..."
            clearable
            style="width: 300px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select v-model="selectedCategory" placeholder="选择分类" clearable style="width: 200px">
            <el-option label="全部分类" value="" />
            <el-option 
              v-for="category in categories" 
              :key="category" 
              :label="category" 
              :value="category" 
            />
          </el-select>
          
          <el-button-group>
            <el-button 
              :type="viewMode === 'grid' ? 'primary' : 'default'"
              size="small"
              @click="viewMode = 'grid'"
            >
              <el-icon><Grid /></el-icon>
            </el-button>
            <el-button 
              :type="viewMode === 'list' ? 'primary' : 'default'"
              size="small"
              @click="viewMode = 'list'"
            >
              <el-icon><List /></el-icon>
            </el-button>
          </el-button-group>
        </div>
        
        <div class="action-controls">
          <el-button @click="goToDashboard">
            <el-icon><Monitor /></el-icon>
            仪表板
          </el-button>
          <el-button type="primary" @click="refreshWidgets">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 组件统计 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number">{{ widgetStore.widgets.length }}</div>
            <div class="stat-label">可用组件</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number enabled">{{ enabledWidgetsCount }}</div>
            <div class="stat-label">已启用</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number disabled">{{ disabledWidgetsCount }}</div>
            <div class="stat-label">已禁用</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number">{{ categories.length }}</div>
            <div class="stat-label">分类数</div>
          </div>
        </el-col>
      </el-row>

      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'" class="widgets-grid">
        <div 
          v-for="widget in filteredWidgets" 
          :key="widget.id"
          class="widget-card"
        >
          <div class="widget-header">
            <div class="widget-icon">
              <el-icon :size="32" :color="getWidgetColor(widget.category)">
                <component :is="getWidgetIcon(widget.category)" />
              </el-icon>
            </div>
            <div class="widget-info">
              <h3>{{ widget.name }}</h3>
              <p class="widget-version">v{{ widget.version }}</p>
            </div>
          </div>
          
          <div class="widget-content">
            <p class="widget-description">{{ widget.description }}</p>
            
            <div class="widget-meta">
              <el-tag size="small" :type="getWidgetTagType(widget.category)">
                {{ widget.category }}
              </el-tag>
              <span class="widget-author">{{ widget.author_name || '系统' }}</span>
            </div>
          </div>
          
          <div class="widget-footer">
            <div class="widget-status">
              <el-tag 
                :type="hasUserWidget(widget.id) ? 'success' : 'info'"
                size="small"
              >
                {{ hasUserWidget(widget.id) ? '已添加' : '未添加' }}
              </el-tag>
            </div>
            
            <div class="widget-actions">
              <el-button 
                v-if="!hasUserWidget(widget.id)"
                type="primary" 
                size="small"
                @click="addWidget(widget)"
              >
                添加
              </el-button>
              
              <template v-else>
                <el-button 
                  size="small"
                  @click="showUserWidgetConfiguration(getUserWidget(widget.id)!)"
                >
                  配置
                </el-button>
                <el-button 
                  size="small"
                  @click="toggleUserWidget(getUserWidget(widget.id)!)"
                >
                  {{ getUserWidget(widget.id)?.is_enabled ? '禁用' : '启用' }}
                </el-button>
                <el-button 
                  size="small"
                  type="danger"
                  @click="removeUserWidget(getUserWidget(widget.id)!)"
                >
                  移除
                </el-button>
              </template>
              
              <el-button size="small" @click="showWidgetInfo(widget)">
                详情
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 列表视图 -->
      <div v-else class="widgets-list">
        <el-table :data="filteredWidgets" style="width: 100%">
          <el-table-column prop="name" label="组件名称" width="200">
            <template #default="{ row }">
              <div class="widget-name-cell">
                <el-icon :size="16" :color="getWidgetColor(row.category)">
                  <component :is="getWidgetIcon(row.category)" />
                </el-icon>
                <span>{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="description" label="描述" />
          
          <el-table-column prop="category" label="分类" width="120">
            <template #default="{ row }">
              <el-tag size="small" :type="getWidgetTagType(row.category)">
                {{ row.category }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="version" label="版本" width="100">
            <template #default="{ row }">
              <span class="widget-version">v{{ row.version }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="author_name" label="作者" width="120" />
          
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag 
                :type="hasUserWidget(row.id) ? 'success' : 'info'"
                size="small"
              >
                {{ hasUserWidget(row.id) ? '已添加' : '未添加' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button 
                v-if="!hasUserWidget(row.id)"
                type="primary" 
                size="small"
                @click="addWidget(row)"
              >
                添加
              </el-button>
              
              <template v-else>
                <el-button 
                  size="small"
                  @click="showUserWidgetConfiguration(getUserWidget(row.id)!)"
                >
                  配置
                </el-button>
                <el-button 
                  size="small"
                  @click="toggleUserWidget(getUserWidget(row.id)!)"
                >
                  {{ getUserWidget(row.id)?.is_enabled ? '禁用' : '启用' }}
                </el-button>
              </template>
              
              <el-button size="small" @click="showWidgetInfo(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    
    <!-- 组件详情对话框 -->
    <el-dialog
      v-model="showWidgetDetails"
      :title="selectedWidget?.name"
      width="600px"
    >
      <div v-if="selectedWidget" class="widget-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="组件名称">
            {{ selectedWidget.name }}
          </el-descriptions-item>
          <el-descriptions-item label="版本">
            v{{ selectedWidget.version }}
          </el-descriptions-item>
          <el-descriptions-item label="作者">
            {{ selectedWidget.author_name || '系统' }}
          </el-descriptions-item>
          <el-descriptions-item label="分类">
            <el-tag :type="getWidgetTagType(selectedWidget.category)">
              {{ selectedWidget.category }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述">
            {{ selectedWidget.description }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedWidget.is_active ? 'success' : 'danger'">
              {{ selectedWidget.is_active ? '活跃' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(selectedWidget.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDate(selectedWidget.updated_at) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="selectedWidget.config_schema" class="config-schema">
          <h4>配置架构</h4>
          <pre>{{ formatConfigSchema(selectedWidget.config_schema) }}</pre>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showWidgetDetails = false">关闭</el-button>
          <el-button 
            v-if="selectedWidget && !hasUserWidget(selectedWidget.id)"
            type="primary" 
            @click="addWidget(selectedWidget)"
          >
            添加到仪表板
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户组件配置对话框 -->
    <el-dialog
      v-model="showUserWidgetConfig"
      :title="`配置 ${selectedUserWidget?.widget?.name}`"
      width="600px"
    >
      <WidgetConfig 
        v-if="selectedUserWidget"
        :widget="selectedUserWidget"
        @save="saveUserWidgetConfig"
        @cancel="showUserWidgetConfig = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useWidgetStore } from '@/stores/widget'
import WidgetConfig from '@/components/WidgetConfig.vue'
import type { Widget, UserWidget } from '@/stores/widget'

const router = useRouter()
const widgetStore = useWidgetStore()

// 视图模式
const viewMode = ref<'grid' | 'list'>('grid')

// 搜索和筛选
const searchQuery = ref('')
const selectedCategory = ref('')

// 对话框状态
const showWidgetDetails = ref(false)
const showUserWidgetConfig = ref(false)
const selectedWidget = ref<Widget | null>(null)
const selectedUserWidget = ref<UserWidget | null>(null)

// 分类列表
const categories = ref<string[]>([])

// 计算属性
const filteredWidgets = computed(() => {
  let widgets = widgetStore.widgets

  // 按分类筛选
  if (selectedCategory.value) {
    widgets = widgets.filter(w => w.category === selectedCategory.value)
  }

  // 按搜索词筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    widgets = widgets.filter(w => 
      w.name.toLowerCase().includes(query) ||
      w.description.toLowerCase().includes(query) ||
      w.category.toLowerCase().includes(query)
    )
  }

  return widgets
})

const enabledWidgetsCount = computed(() => widgetStore.getEnabledUserWidgets().length)
const disabledWidgetsCount = computed(() => widgetStore.userWidgets.length - enabledWidgetsCount.value)

// 获取组件图标
function getWidgetIcon(category?: string): string {
  const iconMap: Record<string, string> = {
    'default': 'Grid',
    'system': 'Setting',
    'tool': 'Tool',
    'dashboard': 'Monitor',
    'communication': 'Message',
    'file': 'Document',
    'entertainment': 'VideoPlay'
  }
  return iconMap[category || 'default'] || 'Grid'
}

// 获取组件颜色
function getWidgetColor(category?: string): string {
  const colorMap: Record<string, string> = {
    'default': '#409EFF',
    'system': '#909399',
    'tool': '#E6A23C',
    'dashboard': '#67C23A',
    'communication': '#8B5CF6',
    'file': '#F56C6C',
    'entertainment': '#FF6B6B'
  }
  return colorMap[category || 'default'] || '#409EFF'
}

// 获取组件标签类型
function getWidgetTagType(category?: string): string {
  const typeMap: Record<string, string> = {
    'default': 'primary',
    'system': 'info',
    'tool': 'warning',
    'dashboard': 'success',
    'communication': 'danger',
    'file': 'danger',
    'entertainment': 'danger'
  }
  return typeMap[category || 'default'] || 'primary'
}

// 检查用户是否已有组件
function hasUserWidget(widgetId: number): boolean {
  return widgetStore.hasUserWidget(widgetId)
}

// 获取用户组件
function getUserWidget(widgetId: number): UserWidget | null {
  const userWidgetId = widgetStore.getUserWidgetId(widgetId)
  return userWidgetId ? widgetStore.userWidgets.find(w => w.id === userWidgetId) || null : null
}

// 刷新组件列表
async function refreshWidgets() {
  try {
    await Promise.all([
      widgetStore.fetchWidgets(),
      widgetStore.fetchUserWidgets()
    ])
    ElMessage.success('组件列表已刷新')
  } catch (error: any) {
    ElMessage.error('刷新失败')
  }
}

// 添加组件
async function addWidget(widget: Widget) {
  if (hasUserWidget(widget.id)) {
    ElMessage.warning('组件已添加')
    return
  }

  try {
    await widgetStore.addUserWidget(widget.id)
    ElMessage.success(`组件 "${widget.name}" 已添加`)
  } catch (error: any) {
    ElMessage.error(error.message || '添加组件失败')
  }
}

// 删除用户组件
async function removeUserWidget(userWidget: UserWidget) {
  try {
    await widgetStore.deleteUserWidget(userWidget.id)
    ElMessage.success(`组件 "${userWidget.widget?.name}" 已移除`)
  } catch (error: any) {
    ElMessage.error(error.message || '移除组件失败')
  }
}

// 切换组件状态
async function toggleUserWidget(userWidget: UserWidget) {
  try {
    await widgetStore.toggleUserWidget(userWidget.id)
    ElMessage.success(`组件 "${userWidget.widget?.name}" 已${userWidget.is_enabled ? '启用' : '禁用'}`)
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 显示组件详情
function showWidgetInfo(widget: Widget) {
  selectedWidget.value = widget
  showWidgetDetails.value = true
}

// 显示用户组件配置
function showUserWidgetConfiguration(userWidget: UserWidget) {
  selectedUserWidget.value = userWidget
  showUserWidgetConfig.value = true
}

// 保存用户组件配置
async function saveUserWidgetConfig(config: any) {
  if (!selectedUserWidget.value) return
  
  try {
    await widgetStore.updateUserWidget(selectedUserWidget.value.id, config)
    showUserWidgetConfig.value = false
    ElMessage.success('组件配置已保存')
  } catch (error: any) {
    ElMessage.error(error.message || '保存配置失败')
  }
}

// 格式化日期
function formatDate(dateString: string): string {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 格式化配置架构
function formatConfigSchema(schema: string): string {
  try {
    return JSON.stringify(JSON.parse(schema), null, 2)
  } catch {
    return schema
  }
}

// 导航到仪表板
function goToDashboard() {
  router.push('/dashboard')
}

// 初始化
onMounted(async () => {
  try {
    await Promise.all([
      widgetStore.fetchWidgets(),
      widgetStore.fetchUserWidgets()
    ])
    
    // 获取分类列表
    const uniqueCategories = [...new Set(widgetStore.widgets.map(w => w.category).filter(Boolean))]
    categories.value = uniqueCategories
  } catch (error: any) {
    ElMessage.error('加载组件列表失败')
  }
})
</script>

<style scoped>
.modules-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.search-controls {
  display: flex;
  gap: 12px;
  flex: 1;
}

.action-controls {
  display: flex;
  gap: 12px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: var(--bg-color-secondary);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-color);
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: var(--text-color);
  margin-bottom: 8px;
}

.stat-number.enabled {
  color: var(--success-color);
}

.stat-number.disabled {
  color: var(--error-color);
}

.stat-label {
  font-size: 14px;
  color: var(--text-color-secondary);
}

.widgets-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.widget-card {
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: 20px;
  background: var(--card-bg);
  transition: all 0.3s ease;
}

.widget-card:hover {
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
}

.widget-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
}

.widget-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-color-secondary);
  flex-shrink: 0;
}

.widget-info h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.widget-version {
  margin: 0;
  font-size: 12px;
  color: var(--text-color-secondary);
}

.widget-content {
  margin-bottom: 16px;
}

.widget-description {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: var(--text-color-secondary);
  line-height: 1.5;
}

.widget-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.widget-author {
  font-size: 12px;
  color: var(--text-color-secondary);
}

.widget-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.widget-status {
  display: flex;
  align-items: center;
}

.widget-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.widgets-list {
  margin-top: 20px;
}

.widget-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.widget-details {
  padding: 10px 0;
}

.config-schema {
  margin-top: 20px;
}

.config-schema h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-color);
}

.config-schema pre {
  background: var(--bg-color-secondary);
  padding: 12px;
  border-radius: var(--radius-md);
  font-size: 12px;
  overflow-x: auto;
  max-height: 200px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .modules-container {
    padding: 16px;
  }
  
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-controls {
    flex-direction: column;
  }
  
  .widgets-grid {
    grid-template-columns: 1fr;
  }
  
  .widget-footer {
    flex-direction: column;
    gap: 12px;
  }
  
  .widget-actions {
    justify-content: center;
  }
}
</style>
